<?php

// sku 标签类
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class TagController extends Controller
{
	
	// 标签库
	public function index( Request $request )
	{
	
		// 获取路由
		$route_array = request()->route()->getAction();
		$controller = explode("\\",$route_array['controller']);
		$result = explode("@",$controller[3]);
		// 控制器 	$result[0];
		// 方法 	$result[1];
		$auth_final = '';
		foreach( Session::get('auths') as $key=> $auth_info )
		{
			// 符合条件
			if( $auth_info['controller']==$result[0] && $auth_info['func']==$result[1] )
			{
				$auth_final = true;
				break;
			}else
			{
				$auth_final = false;
			}
		} 
		// 权限验证失败
		if( !$auth_final )
		{
			return back()->with( ['authinfo'=>'没有此项权限'] );
		}
		
		// 获取搜索内容
		$keyword = $request -> input('keyword',"");
		if( empty($keyword) )
		{
			// 为空 说明没有搜索
			$one = 'id';
			$two = '!=';
			$three = '0';
		}else
		{
			$one = 'name';
			$two = 'like';
			$three = '%'.$keyword.'%';
		}
		
		// 获取所有标签
		$tags = DB::table('tag')
				-> where( $one,$two,$three )
				-> paginate(20);
		return view( 'tag.list',[ 'tags'=>$tags,'request'=>$keyword ] );
	}
	
	
	// 删除标签
	public function delTags( Request $request )
	{
		// 包含 标签id
		$data = $request -> except('_token');
		// 清除无效值
		unset($data['all'][0]);	
		
		foreach( $data['all'] as $key => $tag_id )
		{
			$history = DB::table('tag_record as tr')
				-> select('t.name','t.id')
				-> leftJoin('tag as t','t.id','=','tr.tag_id')
				-> where('tr.tag_id',$tag_id)
				-> first();
			if( !empty($history) )
			{
				$this -> ajAxReturn( $history->name.' 下有sku 无法删除');
			}
		}
		// 批量删除
		$res = DB::table('tag')
				-> whereIn( 'id',$data['all'] )
				-> delete();
		if( $res )
		{
			$this -> ajAxReturn('删除成功');
		}
		$this -> ajAxReturn('删除失败');
	
	}
	
	
}
